﻿using FormsAuthWeb.Models;
using FormsAuthWeb.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Web.Http;

namespace FormsAuthWeb.WebApis
{
    public class LoginApiController : ApiController
    {
        public string GetMessage()
        {
            // 获取当前 Windows 身份
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            // 创建 WindowsPrincipal 对象
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            // 检查当前用户是否是管理员
            bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            // 输出结果
            return $"当前用户：{identity.Name}，是否是管理员：{isAdmin}";
        }

        [HttpPost]
        public MessageInfo UserLogin(LoginData loginData)
        {
            MessageInfo result = new MessageInfo();
            if (loginData == null)
            {
                result.Success = false;
                result.Message = "登录失败";
                return result;
            }
            else
            {
                UserInfo userinfo = new UserInfo();
                userinfo.UserId = loginData.UserId;
                userinfo.RoleId = loginData.RoleId;
                userinfo.UserName = loginData.UserName;
                userinfo.MobilePhone = loginData.MobilePhone;
                // 登录状态100分钟内有效
                FormsPrincipal<UserInfo>.SignIn(loginData.LoginName, userinfo, 100);

                result.Success = true;
                result.Message = "登录成功";
                return result;
            }
        }
    }
}